<template>
	<view class="container">
		<!-- 优惠券列表 -->
		<view class="coupon-list">
			<view v-for="(couponItem, index) in couponList" :key="couponItem.id" class="coupon-item"
				:class="{ 'is-invalid': couponItem.is_invalid }" @click.stop="goToShopList(couponItem)">
				<view class="coupon-left">
					<view class="amount-wrapper">
						<text class="amount-symbol">¥</text>
						<text class="amount-value">{{ couponItem.coupon.amount }}</text>
					</view>
					<view class="coupon-condition">
						满{{ couponItem.coupon.min_consumption }}可用
					</view>
				</view>
				<view class="coupon-right">
					<view class="coupon-info">
						<view class="coupon-name">{{ couponItem.name }}</view>
						<view class="coupon-validity">
							有效期至：{{ formatDate(couponItem.coupon.end_time) }}
						</view>
						<view v-if="getApplicableRooms(couponItem)" class="coupon-rooms">
							<u-icon name="home" size="24" class="room-icon"></u-icon>
							<text>{{ getApplicableRooms(couponItem) }}</text>
						</view>
					</view>
					<view class="use-button">
						<text>立即使用</text>
					</view>
				</view>
			</view>

			<!-- 空状态 -->
			<view class="empty-state" v-if="couponList.length === 0 && !isLoading">
				<view class="empty-icon">🎫</view>
				<text class="empty-text">暂无可用优惠券</text>
				<text class="empty-desc">快去获取更多优惠券吧</text>
			</view>

			<!-- 加载状态 -->
			<view class="loading-state" v-if="isLoading">
				<text class="loading-text">加载中...</text>
			</view>
		</view>
	</view>
</template>

<script>
import request from '@/common/request.js';

export default {
	data() {
		return {
			couponList: [],
			selectedCoupon: null,
			totalPrice: 0,
			roomId: '',
			shopId: '',
			params: {},
			isLoading: false,
			orderData: {},
			page: 1
		}
	},
	onLoad(options) {
		console.log('优惠券页面接收参数:', options);
		// 解析传入的参数
		if (options.params) {
			try {
				this.params = JSON.parse(decodeURIComponent(options.params));
				console.log('解析后的参数:', this.params);
				this.totalPrice = parseFloat(this.params.totalPrice || 0);
				this.roomId = this.params.roomId || '';
				this.shopId = this.params.shopId || '';
				this.orderData = this.params.orderData || {};
			} catch (e) {
				console.error('解析参数失败:', e);
			}
		}
		// 接收已选择的优惠券（从其他页面返回时）
		if (options.selectedCoupon) {
			try {
				this.selectedCoupon = JSON.parse(decodeURIComponent(options.selectedCoupon));
				console.log('已选择的优惠券:', this.selectedCoupon);
			} catch (e) {
				console.error('解析已选优惠券失败:', e);
			}
		}
		this.getCouponList();
	},
	methods: {
		// 获取优惠券列表
		getCouponList() {
			this.isLoading = true;
			let opts = {
				url: `/api/user/getUsersCoupon?page=${this.page}`,
				method: 'get',
			};

			request.httpTokenRequest(opts).then(res => {
				console.log('获取优惠券列表响应:', res);
				this.isLoading = false;

				if (res && res.data && res.data.code == 1) {
					const newCoupons = res.data.data || [];
					const now = new Date().getTime(); // Get current timestamp in milliseconds

					this.couponList = newCoupons.data.map(coupon => {
						const endTime = coupon.coupon.end_time * 1000; // Convert to milliseconds
						coupon.is_invalid = endTime < now;
						return coupon;
					});

					console.log('优惠券列表:', this.couponList);
				} else {
					uni.showToast({
						title: res.data?.msg || '获取优惠券失败',
						icon: 'none'
					});
				}
			}).catch(err => {
				this.isLoading = false;
				console.error('获取优惠券列表失败:', err);
				uni.showToast({
					title: '获取优惠券失败',
					icon: 'none'
				});
			});
		},

		// 获取优惠券名称
		getCouponName(couponItem) {
			// 如果有room_name，解析并显示
			if (couponItem.room_name) {
				try {
					const roomNames = JSON.parse(couponItem.room_name);
					if (Array.isArray(roomNames) && roomNames.length > 0) {
						return `${roomNames[0]}专用券`;
					}
				} catch (e) {
					console.error('解析房间名称失败:', e);
				}
			}
			console.log(couponItem, 'couponItem.coupon.amount');


			// 默认显示优惠券金额
			return `${couponItem.coupon.amount}元优惠券`;
		},

		// 判断优惠券是否可用
		isCouponAvailable(couponItem) {
			console.log('判断优惠券可用性:', couponItem);

			// 检查优惠券状态
			if (couponItem.status !== "1") {
				console.log('优惠券状态不可用:', couponItem.status);
				return false;
			}

			// 检查最低消费金额
			const minConsumption = parseFloat(couponItem.coupon.min_consumption || 0);
			if (minConsumption > 0 && this.totalPrice < minConsumption) {
				console.log('订单金额不满足最低消费:', this.totalPrice, '<', minConsumption);
				return false;
			}

			// 检查有效期 (end_time是时间戳)
			if (couponItem.coupon.end_time) {
				const expireTime = new Date(couponItem.coupon.end_time * 1000);
				const now = new Date();
				if (expireTime < now) {
					console.log('优惠券已过期:', expireTime, '<', now);
					return false;
				}
			}

			// 检查开始时间 (start_time是时间戳)
			if (couponItem.coupon.start_time) {
				const startTime = new Date(couponItem.coupon.start_time * 1000);
				const now = new Date();
				if (startTime > now) {
					console.log('优惠券未到使用时间:', startTime, '>', now);
					return false;
				}
			}

			console.log('优惠券可用');
			return true;
		},

		// 选择优惠券
		selectCoupon(couponItem) {
			console.log('选择优惠券:', couponItem);
			return
			uni.navigateTo({
				url: '/pages/user/coupon-detail?coupon_id' + couponItem.coupon_id,
			})
		},

		// 选择不使用优惠券
		selectNoCoupon() {
			console.log('选择不使用优惠券');
			this.selectedCoupon = null;
		},

		// 确认选择
		confirmSelection() {
			console.log('确认选择，当前选中:', this.selectedCoupon);

			// 构建返回参数
			const returnParams = {
				...this.params
			};

			if (this.selectedCoupon) {
				returnParams.selectedCoupon = encodeURIComponent(JSON.stringify(this.selectedCoupon));
			} else {
				// 确保清除之前选择的优惠券
				delete returnParams.selectedCoupon;
			}

			console.log('返回参数:', returnParams);

			// 获取页面栈 - uni-app中getCurrentPages是全局函数
			const pages = getCurrentPages();
			const prevPage = pages[pages.length - 2];

			if (prevPage) {
				console.log('返回到页面:', prevPage.route);

				// 构建返回URL
				const paramString = Object.keys(returnParams)
					.filter(key => returnParams[key] !== undefined && returnParams[key] !== null)
					.map(key => `${key}=${returnParams[key]}`)
					.join('&');

				const returnUrl = `/${prevPage.route}${paramString ? '?' + paramString : ''}`;
				console.log('返回URL:', returnUrl);

				uni.redirectTo({
					url: returnUrl,
					success: () => {
						console.log('返回成功');
					},
					fail: (err) => {
						console.error('返回失败:', err);
						// 如果redirectTo失败，尝试使用navigateBack
						uni.navigateBack({
							delta: 1
						});
					}
				});
			} else {
				console.log('没有上一页，直接返回');
				uni.navigateBack({
					delta: 1
				});
			}
		},

		// 格式化日期 (处理时间戳)
		formatDate(timestamp) {
			if (!timestamp) return '';

			const date = new Date(timestamp * 1000); // 转换为毫秒
			const year = date.getFullYear();
			const month = ('0' + (date.getMonth() + 1)).slice(-2);
			const day = ('0' + date.getDate()).slice(-2);
			return `${year}-${month}-${day}`;
		},

		// 返回
		goBack() {
			uni.navigateBack();
		},

		getApplicableRooms(couponItem) {
			if (!couponItem.room_name) return '';
			try {
				const roomNames = JSON.parse(couponItem.room_name);
				if (Array.isArray(roomNames) && roomNames.length > 0) {
					return `可用房间: ${roomNames.join(', ')}`;
				}
			} catch (e) {
				// Not a valid JSON, maybe it's a plain string
				if (typeof couponItem.room_name === 'string' && couponItem.room_name.trim() !== '') {
					return `可用房间: ${couponItem.room_name}`;
				}
			}
			return '';
		},

		goToShopList(couponItem) {
			if (couponItem.is_invalid) {
				this.$u.toast('该优惠券已失效');
				return;
			}
			const rooms = this.getApplicableRooms(couponItem);
			const roomName = rooms.replace('可用房间: ', ''); // Extract room name
			if (roomName) {
				uni.navigateTo({
					url: `/pages/shop/shop-list?keyword=${encodeURIComponent(roomName)}`
				});
			}
		},

		useCouponNow(couponItem) {
			// 如果是无效券，则不执行任何操作
			if (couponItem.is_invalid) {
				this.$u.toast('该优惠券已失效');
				return;
			}
			uni.switchTab({
				url: '/pages/shop/shop-list'
			});
		}
	}
}
</script>

<style lang="scss">
.container {
	min-height: 100vh;
	background-color: #f5f6fa;
	padding: 24rpx;
}

.coupon-list {
	.coupon-item {
		display: flex;
		margin-bottom: 24rpx;
		background-color: #fff;
		border-radius: 16rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
		overflow: hidden;
		position: relative;

		&::before,
		&::after {
			content: '';
			position: absolute;
			width: 40rpx;
			height: 40rpx;
			background-color: #f5f6fa;
			border-radius: 50%;
			left: 230rpx; // Adjust based on .coupon-left width
		}

		&::before {
			top: -20rpx;
		}

		&::after {
			bottom: -20rpx;
		}

		&.is-invalid {
			filter: grayscale(1);
			opacity: 0.7;
		}

		.coupon-left {
			width: 250rpx;
			background: linear-gradient(135deg, #ff8c00, #ff4500);
			color: #fff;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			padding: 20rpx;
			position: relative;
			border-right: 2rpx dashed #fff;

			.amount-wrapper {
				display: flex;
				align-items: baseline;
				line-height: 1;
			}

			.amount-symbol {
				font-size: 32rpx;
				margin-right: 8rpx;
			}

			.amount-value {
				font-size: 72rpx;
				font-weight: bold;
			}

			.coupon-condition {
				font-size: 24rpx;
				margin-top: 16rpx;
				background-color: rgba(255, 255, 255, 0.2);
				padding: 4rpx 12rpx;
				border-radius: 20rpx;
			}
		}

		.coupon-right {
			flex: 1;
			padding: 24rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.coupon-info {
				display: flex;
				flex-direction: column;
				justify-content: center;
				flex: 1;
				min-width: 0;

				.coupon-name {
					font-size: 30rpx;
					font-weight: bold;
					color: #333;
					margin-bottom: 12rpx;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
				}

				.coupon-validity {
					font-size: 22rpx;
					color: #999;
					margin-bottom: 8rpx;
				}

				.coupon-rooms {
					display: flex;
					align-items: center;
					font-size: 22rpx;
					color: #666;

					.room-icon {
						margin-right: 8rpx;
					}
				}
			}

			.use-button {
				writing-mode: vertical-rl;
				background: #ff5a5a;
				color: white;
				padding: 20rpx 12rpx;
				border-radius: 8rpx;
				font-size: 28rpx;
				letter-spacing: 4rpx;
				margin-left: 20rpx;
				cursor: pointer;
			}
		}
	}
}

.empty-state,
.loading-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 120rpx 40rpx;
}

.empty-icon {
	font-size: 120rpx;
	margin-bottom: 40rpx;
	opacity: 0.3;
}

.empty-text,
.loading-text {
	font-size: 32rpx;
	color: #666;
	margin-bottom: 16rpx;
}

.empty-desc {
	font-size: 28rpx;
	color: #999;
}

.bottom-bar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #fff;
	padding: 30rpx;
	border-top: 2rpx solid #e0e0e0;
	display: flex;
	justify-content: space-between;
	align-items: center;
	box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.price-info {
	display: flex;
	flex-direction: column;
}

.original-price {
	font-size: 24rpx;
	color: #666;
	margin-bottom: 8rpx;
}

.final-price {
	font-size: 28rpx;
	font-weight: bold;
	color: #ff6b6b;
}

.confirm-btn {
	background-color: #007aff;
	color: #fff;
	border: none;
	padding: 0 40rpx;
	height: 80rpx;
	line-height: 80rpx;
	border-radius: 40rpx;
	font-size: 28rpx;
	font-weight: 500;
	margin: 0;
}
</style>